// 将源数据list中字段名改为指定字段名后存入target中
// 即 data = [ { originalKey: value1, originalLabel: value2, ... } ] ==>  target = [ { nodeKey: value1, nodeLabel: value2, ... } ]
function transformListByField(list = [], target = [], originalKey = 'code', originalLabel = 'label', nodeKey = 'field', nodeLabel = 'title', childrenField = 'children') {
  if (!list.length) {
    return
  }

  list.forEach(node => {
    const { [originalKey]: keyValue, [originalLabel]: labelValue, [childrenField]: children = [], ...reset } = node
    const tempNode = {
      [nodeKey]: keyValue,
      [nodeLabel]: labelValue,
      ...reset
    }
    if (children.length) {
      tempNode[childrenField] = []
      transformListByField(children, tempNode[childrenField], originalKey, originalLabel, nodeKey, nodeLabel, childrenField)
    }
    target.push(tempNode)
  })
}

// 遍历多层结构，执行相关逻辑
function traverseList (list = [], cbk = null, children = 'children') { // 展开树
  if (!list.length) {
    return
  }

  list.forEach(node => {
    typeof cbk === 'function' && cbk(node)
    Array.isArray(node[children]) && node[children].length && traverseList(node[children], cbk, children)
  })
}

// 遍历多层结构，查找指定节点
// node对象及其children元素中，field字段值包含在target数组中，则返回true
function findTarget (node = {}, target = [], field = 'field', children = 'children') {
  let result = false
  if (target.includes(node[field])) {
    result = true
  } else if (Array.isArray(node[children]) && node[children].length) {
    const list = node[children]
    for (let i = 0; i < list.length; i++) {
      const tempNode = list[i]
      result = findTarget(tempNode, target, field, children)
      if (result) {
        break
      }
    }
  }

  return result
}

// 对象a,b按指定字段field排序
function sortByField (a, b, field, order = '') {
  if (typeof a[field] === 'number') { // 数组排序
    if (order === 'asc') {
      return a[field] - b[field]
    } else if (order === 'desc') {
      return b[field] - a[field]
    } else {
      return 0
    }
  } else { // 字符串排序
    if (order === 'asc') {
      return a[field].localeCompare(b[field])
    } else if (order === 'desc') {
      return b[field].localeCompare(a[field])
    } else {
      return 0
    }
  }
}

// 虚拟滚动配置
const virtualScrollOption = {
  enable: false, // 是否开启虚拟滚动
  scrolling: null
}

// 分页配置
const defaultPagination = {
  enable: false, // 是否显示分页
  total: 0, // 总个数
  pageIndex: 1, // 当前页码 从1开始
  pageSize: 30, // 每页个数
  layout: ['total', 'prev', 'pager', 'next', 'sizer', 'jumper'], // 当前显示哪些组件
  pageSizeOption: [30, 50, 80] // 下拉配置每页显示个数
}

// 行样式
const defaultRowStyle = {
  hoverHighlight: true,
  clickHighlight: true,
  stripe: true
}

// 展开行默认配置
const defaultExpandOption = {
  expandable: false
}

export {
  traverseList,
  findTarget,
  sortByField,
  transformListByField,
  virtualScrollOption,
  defaultPagination,
  defaultRowStyle,
  defaultExpandOption
}
